//
//  Service_DetailController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/12/21.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "Service_DetailController.h"

//untils
#import "UIColor+Hex.h"
#import "UIImage+ColorToImage.h"
#import "Global.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "NSString+Conversion.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "FMDBManager.h"
#import "MJRefresh.h"
//view
#import "ServerDetailHeaderView.h"
#import "ServerDetailSelectServerTypeCell.h"
#import "ServerDetailPriceIntroducedCell.h"
#import "Strore_detailView.h"
//controller
#import "Strore_productTextAndImageInfoWebController.h"
#import "SureOrderController.h"
#import "Login_Controller.h"
#define kbottomViewHeight 49
@interface Service_DetailController ()<UITableViewDataSource,UITableViewDelegate,ServerDetailSelectServerTypeCellDelegate,UIWebViewDelegate>
{
    NSInteger _selectedServiceItemIndex;
}
@property(strong,nonatomic)UITableView *tableView;
@property(nonatomic, strong)UIView *tableFooterView;
@property(nonatomic, strong)UIScrollView *rootScrollView;
@property(nonatomic, strong)UIWebView *image_textView;//图文详情
@property(nonatomic, strong)ServerDetailHeaderView *headerView;
@property(nonatomic, strong)NSMutableDictionary *dataSourceDic;
@property(nonatomic, assign)BOOL isWebFinshLoaded;//web页面是否完成加载
@property(nonatomic, strong)UIView *bottomView;
//往数据库存 中途转换
@property(nonatomic, strong)NSMutableDictionary *dicData;
@end

@implementation Service_DetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackNavItem];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    self.title = self.shopName;
    _dataSourceDic = [[NSMutableDictionary alloc]init];
    _dicData=[[NSMutableDictionary alloc]init];
    _selectedServiceItemIndex = 0;
    [self setupSubView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadServiceDetailData];
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:NO];
}
#pragma mark -- request Data
- (void)loadServiceDetailData {
//    SIGNATURE			设备识别码
//    STOREID			店铺ID
//    SHOPID			服务商家ID
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.storeID forKey:@"STOREID"];
    [parameter setObject:self.shopID forKey:@"SHOPID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"service/detail" success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            [weakSelf.dataSourceDic removeAllObjects];
            if ([state isEqualToString:@"0"]) {//请求成功
                if ([[dataDic objectForKey:@"OBJECT"] isKindOfClass:[NSDictionary class]]) {
                    NSString *hasDescribe = [NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"HASDESCRIBE"]];
                    [self showTextAndImageWithHasDescribeState:hasDescribe];
                    
                    [_dataSourceDic addEntriesFromDictionary:[dataDic objectForKey:@"OBJECT"]];
                    [_headerView updateWithDataDic:[_dataSourceDic copy]];
                    
                    NSMutableArray *items=[_dataSourceDic objectForKey:@"ITEMS"];
                    [_dicData setValuesForKeysWithDictionary:[items firstObject]];
                    //存入历史表
                    [weakSelf intoWithSqlite];
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
            [weakSelf.tableView reloadData];
        }
        
    } failure:^(bool isFailure) {
        
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
    }];
}

//请求图文详情
- (void)loadTextAndImageData {
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *model = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    NSString *adapterStr = @"";
    adapterStr = @"service/describe";
    [parameter setObject:self.shopID.length == 0 ? @"" : self.shopID forKey:@"SHOPID"];
    [parameter setObject:model.storeID forKey:@"STOREID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:adapterStr success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                NSString *htmlContext = [NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"DESCRIBE"]];
                if (htmlContext.length != 0) {
                    [weakSelf.image_textView loadHTMLString:htmlContext  baseURL:nil];
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
        
    } failure:^(bool isFailure) {
        
        
    }];
}

//服务详情 存历史表    price 为服务次数   oldprice 为商家详情
#pragma mark--将浏览商品详情存入数据库  先查询再插入
-(void)intoWithSqlite
{
    
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *shopID=[NSString stringISNull:mode.storeID];
    NSString *serviceshopID=[NSString stringTransformObject:[_dataSourceDic objectForKey:@"ID"]];
    UIImage *image =[UIImage createImageWithImageUrlString:[NSString stringTransformObject:self.shopImage]];
    if (image==nil) {
        image=[UIImage imageNamed:@"productDetail_Default"];
    }
    NSData *picture =UIImagePNGRepresentation(image);
    NSString *name =[NSString stringTransformObject:[_dataSourceDic objectForKey:@"NAME"]];
    NSString *sercvicenum =[NSString stringTransformObject:[_dataSourceDic objectForKey:@"TOTAL"]];
    NSString *serciceshopdetail=[NSString stringTransformObject:[_dataSourceDic objectForKey:@"COMMENT"]];
    NSDictionary *goodSqlite=[[FMDBManager sharedManager]HistoryQueryDataWithShopID:shopID goodID:@"" serviceshopID:serviceshopID];
    if (goodSqlite.count ==0) {
        [[FMDBManager sharedManager]HistoryInsertWithshopID:shopID goodID:@"" Picture:picture name:name price:@"" oldprice:@"" serviceshopID:serviceshopID serciceshopdetail:serciceshopdetail sercvicenum:sercvicenum isProprietary:@""];
    }else
    {
        [[FMDBManager sharedManager]HistorymodifyDataWithShopID:shopID goodID:@"" name:name price:@"" oldprice:@"" serviceshopID:serviceshopID serciceshopdetail:serciceshopdetail sercvicenum:sercvicenum isProprietary:@""];
    }
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellIdentifierType = @"cellIdentifierType";
        ServerDetailSelectServerTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierType];
        if (!cell) {
            cell = [[ServerDetailSelectServerTypeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierType];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
            [cell.layer setBorderWidth:0.7];
        }
        cell.delegate = self;
        [cell updateDataWithDataArr:[self.dataSourceDic objectForKey:@"ITEMS"]];
        return cell;
    } else  {
        static NSString *cellIdentifierIntroduced = @"cellIdentifierIntroduced";
        ServerDetailPriceIntroducedCell *cellIntroduced= [tableView dequeueReusableCellWithIdentifier:cellIdentifierIntroduced];
        if (!cellIntroduced) {
            cellIntroduced = [[ServerDetailPriceIntroducedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierIntroduced];
            cellIntroduced.selectionStyle = UITableViewCellSelectionStyleNone;
            [cellIntroduced.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
            [cellIntroduced.layer setBorderWidth:0.7];
        }
        cellIntroduced.title = @"价格说明：";
        cellIntroduced.content = [NSString stringTransformObject:[self.dataSourceDic objectForKey:@"COMMENT"]];
        return cellIntroduced;
    }
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[ServerDetailSelectServerTypeCell class]]) {
        return   [((ServerDetailSelectServerTypeCell*) cell) cellFactHight];
    } else if ([cell isKindOfClass:[ServerDetailPriceIntroducedCell class]]) {
        return [((ServerDetailPriceIntroducedCell*) cell) cellFactHeight];
    }
    return cell.frame.size.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark -- UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:webView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[ManagerGlobeUntil sharedManager] hideHUDFromeView:webView];
    NSString *scriptStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
                           "script.type = 'text/javascript';"
                           "script.text = \"function ResizeImages() { "
                           "var myimg,oldwidth;"
                           "var maxwidth=%f;" //缩放系数
                           "for(i=0;i <document.images.length;i++){"
                           "myimg = document.images[i];"
                           "if(myimg.width > maxwidth){"
                           "oldwidth = myimg.width;"
                           "myimg.width = maxwidth;"
                           "}"
                           "}"
                           "}\";"
                           "document.getElementsByTagName('head')[0].appendChild(script);",self.view.bounds.size.width - 2*8];
    [webView stringByEvaluatingJavaScriptFromString:scriptStr];
    
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    self.isWebFinshLoaded = YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    self.isWebFinshLoaded = NO;
    [[ManagerGlobeUntil sharedManager] hideHUDFromeView:webView];
}

#pragma mark -- 刷新事件
- (void)footerRereshing {
    [UIView animateWithDuration:0.3 animations:^{
        self.rootScrollView.contentOffset = CGPointMake(0, self.rootScrollView.bounds.size.height);
    } completion:^(BOOL finished) {
        if (!self.isWebFinshLoaded) {
            [self loadTextAndImageData];
        }
        [self endRefreshing];
    }];
    
    
}
- (void)headerRefreshing {
    [UIView animateWithDuration:0.3 animations:^{
        self.rootScrollView.contentOffset = CGPointMake(0, 0);
    } completion:^(BOOL finished) {
        [self endHeaderRefreshing];
    }];
    
    
}
- (void)endRefreshing {
    [self.tableView footerEndRefreshing];
}

- (void)endHeaderRefreshing {
    [self.image_textView.scrollView headerEndRefreshing];
}

#pragma mark -- 是否展示图文详情
- (void)showTextAndImageWithHasDescribeState:(NSString*)state {
    //是否有图文介绍，1：有，0：没有
    if ([state isEqualToString:@"0"]) {
        self.tableFooterView.hidden = YES;
    } else if ([state isEqualToString:@"1"]) {
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
        [self.tableView setFooterRemindMessageHidden:YES];
        [self.tableView setFooterArrowImageHide:YES];
    }
}

#pragma mark -- 初始化视图
- (void)setupSubView {
    [self.view addSubview:self.rootScrollView];
    [self.rootScrollView addSubview:self.tableView];
    [self.rootScrollView addSubview:self.image_textView];
    [self.view addSubview:self.bottomView];
    
}
- (UIScrollView*)rootScrollView {
    if (!_rootScrollView) {
        CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 64 - kbottomViewHeight);
        UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:frame];
        scrollView.backgroundColor =  [UIColor clearColor];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.scrollEnabled = NO;
        scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds), (CGRectGetHeight(self.view.bounds) - 64 - kbottomViewHeight)*2);
        _rootScrollView = scrollView;
    }
    return _rootScrollView;
}

- (UITableView*)tableView {
    if (!_tableView) {
        CGRect frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-64 - kbottomViewHeight);
        _headerView = [[ServerDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(317)) placeImageName:@"productDetail_Default_loopImage"];
        _headerView.backgroundColor=[UIColor whiteColor];
        [_headerView.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
        [_headerView.layer setBorderWidth:0.7];
         UITableView *tableview = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.tableHeaderView = _headerView;
        tableview.backgroundColor = [UIColor clearColor];
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableview setTableFooterView:self.tableFooterView];
        _tableView = tableview;
    }
    return _tableView;
}

//table 底部视图
- (UIView*)tableFooterView {
    if (!_tableFooterView) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 55)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"上拉查看图文详情" forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor whiteColor]];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 10, VIEW_WIDTH, 45);
        [view addSubview:button];
        _tableFooterView = view;
    }
    return _tableFooterView;
}


- (UIWebView*)image_textView {
    if (!_image_textView) {
        CGRect frame = CGRectMake(CGRectGetMinX(self.tableView.frame)
                                  , CGRectGetMaxY(self.tableView.frame)
                                  , CGRectGetWidth(self.tableView.bounds)
                                  , CGRectGetHeight(self.tableView.bounds));
        UIWebView *webView = [[UIWebView alloc]initWithFrame:frame];
        webView.delegate = self;
        webView.backgroundColor = [UIColor clearColor];
        [webView.scrollView addHeaderWithTarget:self action:@selector(headerRefreshing)];
        [webView.scrollView setHeaderPullToRefreshText:@"下拉回到商品详情"];
        [webView.scrollView setHeaderReleaseToRefreshText:@"释放回到商品详情"];
        [webView.scrollView setHeaderArrowImageHide:YES];
        [webView.scrollView setLastUpdateTimeLabel:YES];
        _image_textView = webView;
    }
    return _image_textView;
}

- (UIView*)bottomView {
    if (!_bottomView) {
        UIView *bottomview =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame),CGRectGetWidth(self.tableView.bounds), 49)];
        
        UIButton *appointments=[UIButton buttonWithType:UIButtonTypeCustom];
        appointments.frame=CGRectMake(15, 3, VIEW_WIDTH-30, 40);
        [appointments setTitle:@"立即预约" forState:UIControlStateNormal];
        appointments.titleLabel.font=[UIFont systemFontOfSize:15];
        UIImage *appointmentsImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#c52720"]
                                                             frame:CGRectMake(0, 0, CGRectGetWidth(appointments.bounds), CGRectGetHeight(appointments.bounds))];
        [appointments setBackgroundImage:appointmentsImage forState:UIControlStateNormal];
        [appointments addTarget:self action:@selector(appointmentsClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomview addSubview:appointments];
        [appointments.layer setMasksToBounds:YES];
        [appointments.layer setCornerRadius:3.0];
        _bottomView = bottomview;
    }
    return _bottomView;
}

#pragma mark -- 立即预约按钮
-(void)appointmentsClick
{
     XiaoQuAndStoreInfoModel *model =[[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    if ([ManagerGlobeUntil sharedManager].transactionLogin) {
        if (model.storeID.integerValue != kDaShiHuiStoreID) {
        NSDictionary *itemDic =  nil;
        NSDictionary *dataDic = nil;
        if ([[self.dataSourceDic objectForKey:@"ITEMS"] count] != 0) {
        itemDic = [[self.dataSourceDic objectForKey:@"ITEMS"] objectAtIndex:_selectedServiceItemIndex];
        dataDic = @{@"STOREID":[NSString stringTransformObject:[self.dataSourceDic objectForKey:@"ID"]],@"SERVICESID":[NSString stringTransformObject:[itemDic objectForKey:@"ID"]],@"MARKETPRICE":[NSString stringTransformObject:[itemDic objectForKey:@"MARKETPRICE"]],@"SELLPRICE":[NSString stringTransformObject:[itemDic objectForKey:@"SELLPRICE"]],@"TITLE":[NSString stringTransformObject:[itemDic objectForKey:@"TITLE"]]};
        }
        SureOrderController *sureOrderVC = [[SureOrderController alloc]init];
        sureOrderVC.orderType = kserviceSureorder;
        [sureOrderVC.serviceDataSource addObject:dataDic];
        [self.navigationController pushViewController:sureOrderVC animated:YES];
        } else {//大实惠总部店不可以下单
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"您所在的小区暂未开通服务，敬请期待！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
        }
    } else {
        Login_Controller *loginVC = [[Login_Controller alloc]init];
        loginVC.supperControllerType = kServiceDetailPushtoLogin_ControllerSupperController;
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}


#pragma mark -- ServerDetailSelectServerTypeCellDelegate
-(void)selectedItemWithTag:(NSInteger)tag itemData:(NSDictionary*)dataDic {
    [_headerView updatePriceWithDataDic:dataDic];
    _selectedServiceItemIndex = tag;
    [_dicData setValuesForKeysWithDictionary:dataDic];
}
- (void)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
